package com.basic.codetool;

import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.basic.common.FuncFile;
import com.basic.common.FuncHttp;

/**
 * 从其他网站CSS文件中获取其图片
 * @author lh
 *
 */
public class CatchCssImg { 
	private String cssPath = null;
	private String domain = null;
	private String saveImgPath = null;
	public static void main(String[] args) throws Exception{
		CatchCssImg ci = new CatchCssImg();
		ci.cssPath = "E:/Work/Project/banyou/WebContent/style/css/css2.css";
		ci.domain = "http://www.duitang.com/";
		ci.saveImgPath = "E:/Work/Project/banyou/WebContent/style/images/by/";
		ci.catchImg();
 
	}
	
	private void catchImg() throws Exception{
		Set<String>  imgs = new HashSet<String>();
		String text = FuncFile.readText(cssPath);
		Pattern p = Pattern.compile("url\\((.*?)\\)");
		Matcher m = p.matcher(text);
		while(m.find()){
			String tmp = m.group(1).toLowerCase();
			if(tmp.contains(".jpg") || tmp.contains(".gif") || tmp.contains(".png")){
				imgs.add(m.group(1).replaceAll("['|\"]", ""));
			}
		}
		for(String img : imgs){
			String filename = findname(img);
			if(img.startsWith("http://")){
				FuncHttp.downloadByUrl(this.saveImgPath+filename, img);
			}else{
				String fullimg = this.domain + img.replaceAll("\\.\\./", ""); 
				FuncHttp.downloadByUrl(this.saveImgPath+filename, fullimg);
			}
			System.out.println(img);
			text = text.replaceAll(Pattern.quote(img) , "../images/"+filename);
		}
		
		FuncFile.insertFile("c:/1.txt", text);
	}
	
	private String findname(String url){
		int index1 = url.lastIndexOf('/');
		int index2 = url.lastIndexOf('?');
		if(index2 > 0){
			return url.substring(index1+1,index2);
		}else{
			return url.substring(index1+1);
		}
		
	}
}
